import { Text, useMessage } from 'alemonjs'
import { validate, selects } from '@src/apps/index'
import { letters } from '@src/db/src/models/user/letters'
import { Op } from 'sequelize'
import { qidToUid } from '@src/apps/tools/qid_goto_uid'

export const regular = /^(!|！|\/)?查阅/

const response = onResponse(selects, async e => {
  const now = Date.now()
  const [message] = useMessage(e)
  const UserId = await qidToUid(e.UserId ?? e.UserKey)

  // 先将 finish_time 小于当前时间的信件 status 批量更新为 3（已过期/已删除）
  await letters.update(
    { status: 3 },
    {
      where: {
        finish_time: { [Op.lt]: now },
        status: { [Op.ne]: 3 }
      }
    }
  )

  // 查询所有未过期信件
  const letterList = await letters.findAllValues({
    where: {
      uid: UserId,
      status: { [Op.ne]: 3 }
    }
  })

  const msg = e.MessageText
  const match = new RegExp('查阅\\s*(\\d+)', 'i').exec(msg)
  const idx = match ? parseInt(match[1], 10) - 1 : -1
  if (!letterList.length || idx < 0 || idx >= letterList.length) {
    message.send(format(Text('\n查无此信件')))
    return
  }

  // 计算剩余时间
  const listWithRemain = letterList.map(l => {
    // finish_time 为 Date 类型，需转为时间戳再计算
    const finishTime = l.finish_time ? new Date(l.finish_time).getTime() : 0
    const remain = finishTime ? finishTime - now : 0
    return { ...l, remain }
  })

  // 按剩余时间升序排序
  listWithRemain.sort((a, b) => a.remain - b.remain)
  const l = listWithRemain[idx]

  // 查阅后将该邮件的status改为1（已读）
  await letters.update(
    { status: 1 },
    {
      where: {
        id: l.id, // 使用邮件ID更新
        status: 0 // 只更新未读状态的邮件
      }
    }
  )

  function formatDate(date: Date | number | string | null | undefined): string {
    if (!date) return '无'
    const d = new Date(date)
    const pad = (n: number) => n.toString().padStart(2, '0')
    return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
  }

  // 剩余时间格式化为天、小时、分钟（向下取整，不显示秒）
  let remainText = '已过期'
  if (l.remain > 0) {
    const days = Math.floor(l.remain / (24 * 60 * 60 * 1000))
    const hours = Math.floor(
      (l.remain % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000)
    )
    const min = Math.floor((l.remain % (60 * 60 * 1000)) / 60000)
    if (days > 0) {
      remainText = `${days}天${hours}小时${min}分`
    } else if (hours > 0) {
      remainText = `${hours}小时${min}分`
    } else {
      remainText = `${min}分`
    }
  }

  // 判断things字段是否为空
  let thingsText = ''
  try {
    const thingsObj =
      typeof l.things === 'string' ? JSON.parse(l.things) : l.things
    if (l.status === 2) {
      thingsText = '(已领取)'
    } else if (
      thingsObj &&
      typeof thingsObj === 'object' &&
      Object.keys(thingsObj).length > 0
    ) {
      // 物品列表不为空且状态不是已领取
      thingsText = Object.entries(thingsObj)
        .map(([key, value]) => `${key}×${value}`)
        .join('，')
    } else {
      thingsText = '(空)'
    }
  } catch {
    thingsText = '(空)'
  }

  let detail = `\n发件人：${l.from}\n剩余时间：${remainText}\n◆◇◆◇◆◇◆◇◆◇◆◇◆◇◆◇◆◇◆◇\n标题：【${l.title}】\n内容：${l.content}\n附件：${thingsText}\n◆◇◆◇◆◇◆◇◆◇◆◇◆◇◆◇◆◇◆◇\n创建时间：${formatDate(l.create_time)}\n过期时间：${formatDate(l.finish_time)}`
  message.send(format(Text(detail)))
  return
})

export default onResponse(selects, [validate, response.current])
